package com.ruoyi.acquisition.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.acquisition.config.InterfaceParamsBean;
import com.ruoyi.acquisition.domain.AcquisitionHostProgram;
import com.ruoyi.acquisition.domain.AcquisitionNetworkAdapterInfo;
import com.ruoyi.acquisition.domain.AcquisitionProgramAccountManage;
import com.ruoyi.acquisition.domain.AcquisitionSoftwareProgramUsageRecord;
import com.ruoyi.acquisition.domain.vo.ApiAcquisitionHostProgramVo;
import com.ruoyi.acquisition.mapper.AcquisitionHostProgramMapper;
import com.ruoyi.acquisition.mapper.AcquisitionNetworkAdapterInfoMapper;
import com.ruoyi.acquisition.mapper.AcquisitionSoftwareProgramUsageRecordMapper;
import com.ruoyi.acquisition.service.IAcquisitionHostProgramDataApi;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author wanglp
 * @create 2024/3/2 23:41
 */
@Service
@Slf4j
public class AcquisitionHostProgramDataApiImpl implements IAcquisitionHostProgramDataApi {
    public static final String PARAMETERS = "Parameters";
    @Autowired
    private AcquisitionNetworkAdapterInfoMapper acquisitionNetworkAdapterInfoMapper;
    @Autowired
    private AcquisitionSoftwareProgramUsageRecordMapper acquisitionSoftwareProgramUsageRecordMapper;
    @Autowired
    private AcquisitionHostProgramMapper acquisitionHostProgramMapper;


    @Override
    public AjaxResult checkReceiveParams(Map<String, List<ApiAcquisitionHostProgramVo>> acquisitionHostProgramMap, HttpServletRequest request, InterfaceParamsBean hostProgramInfo) {
        String messageId = request.getParameter("messageId");
        log.info("checkReceiveParams code:{},bodyRequest:{},messageId:{}", hostProgramInfo.getServiceCode(), JSON.toJSONString(acquisitionHostProgramMap), messageId);
        String openApiSign = request.getHeader("openApiSign");
        if (!hostProgramInfo.isEnabled()) {
            return AjaxResult.error("系统已关闭" + hostProgramInfo.getServiceName() + "接口服务，无法处理该数据。");
        }
        if (!StringUtils.equals(openApiSign, hostProgramInfo.getOpenApiSign())) {
            log.error("checkReceiveParams >> 接口认证失败，code:{} 请求openApiSign:{},messageId:{}", hostProgramInfo.getServiceCode(), openApiSign, messageId);
            return AjaxResult.error("接口认证失败，无法处理该数据。");
        }
        List<ApiAcquisitionHostProgramVo> apiAcquisitionHostProgramVos = acquisitionHostProgramMap.get(PARAMETERS);
        if (CollectionUtils.isEmpty(apiAcquisitionHostProgramVos)) {
            return AjaxResult.error("请求格式不正确，请正确传递参数。");
        }
        Map<String, Object> errorMsg = new HashMap<>();
        apiAcquisitionHostProgramVos.forEach(bean -> {
            Map<String, Object> errorInfo = new HashMap<>();
            if (StringUtils.isBlank(bean.getHostName())) {
                errorInfo.put("hostName", "主机名称必填项");
            }
            if (StringUtils.isBlank(bean.getProgramName())) {
                errorInfo.put("programName", "程序名称必填项");
            }
            if (StringUtils.isBlank(bean.getProgramPath())) {
                errorInfo.put("programPath", "程序路径必填项");
            }
            if (StringUtils.isBlank(bean.getSystemVersion())) {
                errorInfo.put("systemVersion", "系统版本必填项");
            }
            if (StringUtils.isBlank(bean.getProgramFileVersion())) {
                bean.setProgramFileVersion("-");
            }
            if (StringUtils.isBlank(bean.getProgramProductVersion())) {
                bean.setProgramProductVersion("-");
            }

            if (StringUtils.isEmpty(bean.getProcessPid())) {
                errorInfo.put("processPid", "进程ID必填项");
            }
            if (bean.getProgramStartTime() == null) {
                errorInfo.put("programStartTime", "程序启动时间必填项");
            }
            if (StringUtils.isBlank(bean.getLoginAccount())) {
                bean.setLoginAccount("-");
            }
            if (bean.getLoginTime() == null) {
                bean.setLoginTime(new Date());
            }

            if (CollectionUtils.isEmpty(bean.getNetworkAdapterInfoList())) {
                errorInfo.put("networkAdapter", "网卡信息必填项");
            }
            // 校验mac地址
            bean.getNetworkAdapterInfoList().forEach(network -> {
                // 如果重复直接覆盖
                if (StringUtils.isBlank(network.getMacAddress())) {
                    errorInfo.put("MAC", "mac地址必填项");
                }
                if (StringUtils.isBlank(network.getIpAddress())) {
                    errorInfo.put("IP", "ip地址必填项");
                }
            });
            if (MapUtils.isNotEmpty(errorInfo)) {
                errorMsg.put(StringUtils.isBlank(bean.getProgramName()) ? bean.getHostName() + System.nanoTime() : bean.getProgramName(), errorInfo);
            }
        });
        return MapUtils.isEmpty(errorMsg) ? AjaxResult.success() : AjaxResult.error("操作失败", errorMsg);
    }

    @Override
    public AjaxResult insertAcquisitionHostProgramVo(List<ApiAcquisitionHostProgramVo> apiAcquisitionHostProgramVos) {
        List<Map<String, Object>> result = new ArrayList<>();
        apiAcquisitionHostProgramVos.forEach(bean -> {
            Map<String, Object> resultMap = new HashMap<>();
            AcquisitionHostProgram hostProgram = new AcquisitionHostProgram(bean.getHostName(), bean.getProgramName(), bean.getProgramFileVersion(), bean.getProgramProductVersion());
            List<AcquisitionHostProgram> hostProgramList = acquisitionHostProgramMapper.selectAcquisitionHostProgramList(hostProgram);
            if (CollectionUtils.isEmpty(hostProgramList)) {
                hostProgram.setSystemVersion(bean.getSystemVersion());
                hostProgram.setProgramPath(bean.getProgramPath());
                hostProgram.setCreateTime(new Date());
                hostProgram.setUpdateTime(new Date());
                acquisitionHostProgramMapper.insertAcquisitionHostProgram(hostProgram);
            } else {
                hostProgram = hostProgramList.get(0);
            }
            resultMap.put("hostName", hostProgram.getHostName());
            resultMap.put("programName", hostProgram.getProgramName());
            resultMap.put("programFileVersion", hostProgram.getProgramFileVersion());
            resultMap.put("programProductVersion", hostProgram.getProgramProductVersion());
            resultMap.put("id", hostProgram.getId());
            // 处理使用明细
            AcquisitionSoftwareProgramUsageRecord softwareProgramUsageRecord = new AcquisitionSoftwareProgramUsageRecord();
            softwareProgramUsageRecord.setHostProgramId(hostProgram.getId());
            softwareProgramUsageRecord.setProcessPid(bean.getProcessPid());
            softwareProgramUsageRecord.setProgramStartTime(bean.getProgramStartTime());
            List<AcquisitionSoftwareProgramUsageRecord> usageRecords = acquisitionSoftwareProgramUsageRecordMapper.selectAcquisitionSoftwareProgramUsageRecordList(softwareProgramUsageRecord);
            if (CollectionUtils.isEmpty(usageRecords)) {
                softwareProgramUsageRecord.setLastRunTime(bean.getLastRunTime());
                softwareProgramUsageRecord.setLoginAccount(bean.getLoginAccount());
                softwareProgramUsageRecord.setLoginTime(bean.getLoginTime());
                softwareProgramUsageRecord.setCreateTime(new Date());
                softwareProgramUsageRecord.setUpdateTime(new Date());
                acquisitionSoftwareProgramUsageRecordMapper.insertAcquisitionSoftwareProgramUsageRecord(softwareProgramUsageRecord);
            } else {
                softwareProgramUsageRecord = usageRecords.get(0);
                softwareProgramUsageRecord.setLastRunTime(bean.getLastRunTime());
                softwareProgramUsageRecord.setLoginAccount(bean.getLoginAccount());
                softwareProgramUsageRecord.setLoginTime(bean.getLoginTime());
                softwareProgramUsageRecord.setUpdateTime(new Date());
                acquisitionSoftwareProgramUsageRecordMapper.updateAcquisitionSoftwareProgramUsageRecord(softwareProgramUsageRecord);
            }
            resultMap.put("recordId", softwareProgramUsageRecord.getId());
            // 网卡信息
            Long recordId = softwareProgramUsageRecord.getId();
            Long hostProgramId = hostProgram.getId();
            bean.getNetworkAdapterInfoList().forEach(network -> {
                AcquisitionNetworkAdapterInfo adapterInfo = new AcquisitionNetworkAdapterInfo();
                adapterInfo.setHostProgramId(hostProgramId);
                adapterInfo.setMacAddress(network.getMacAddress());
                adapterInfo.setIpAddress(network.getIpAddress());
                List<AcquisitionNetworkAdapterInfo> adapterInfos = acquisitionNetworkAdapterInfoMapper.selectAcquisitionNetworkAdapterInfoList(adapterInfo);
                if (CollectionUtils.isEmpty(adapterInfos)) {
                    adapterInfo.setProgramUsageRecordId(recordId);
                    adapterInfo.setCreateTime(new Date());
                    adapterInfo.setUpdateTime(new Date());
                    acquisitionNetworkAdapterInfoMapper.insertAcquisitionNetworkAdapterInfo(adapterInfo);
                    network.setId(adapterInfo.getId());
                } else {
                    network.setId(adapterInfos.get(0).getId());
                }
                network.setHostProgramId(hostProgramId);
                network.setProgramUsageRecordId(recordId);

            });
            resultMap.put("networkAdapterInfoList", bean.getNetworkAdapterInfoList());
            result.add(resultMap);
        });
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult checkReceiveParamsAccountManage(AcquisitionProgramAccountManage accountManage, HttpServletRequest request, InterfaceParamsBean accountManageConfig) {
        String messageId = request.getParameter("messageId");
        log.info("checkReceiveParamsAccountManage code:{},bodyRequest:{},messageId:{}", accountManageConfig.getServiceCode(), JSON.toJSONString(accountManage), messageId);
        String openApiSign = request.getHeader("openApiSign");
        if (!accountManageConfig.isEnabled()) {
            return AjaxResult.error("系统已关闭" + accountManageConfig.getServiceName() + "接口服务，无法处理该数据。");
        }
        if (!StringUtils.equals(openApiSign, accountManageConfig.getOpenApiSign())) {
            log.error("checkReceiveParamsAccountManage >> 接口认证失败，code:{} 请求openApiSign:{},messageId:{}", accountManageConfig.getServiceCode(), openApiSign, messageId);
            return AjaxResult.error("接口认证失败，无法处理该数据。");
        }
        return AjaxResult.success();
    }
}
